package exhi.action;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;
import com.stp.core.util.DateUtil;
import com.stp.core.util.Identities;
import com.stp.std.entity.AuditLog;

import exhi.entity.EntpSexhi;
import exhi.entity.ExhiCfg;
import exhi.manager.EntpSexhiMng;

@Controller
@RequestMapping("/entp")
public class EntpSexhiAct extends ViewExhiAct {

	private static final String PATH_TABLE = "/small-table";
	private static final String PATH_LIST = "/small-list";
	private static final String PATH_DETAIL = "/small-detail";
	private static final String PATH_VIEW = "/small-view";
	private static final String PATH_SAVE = "/small-save";
	private static final String PATH_DELETE = "/small-delete";
	private static final String PATH_SB = "/small-sb";

	// 小型or国内展表格
	@RequestMapping(PATH_TABLE)
	public void table(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			ModelMap model) {
		model.addAttribute("code", code);
	}

	// 权限json数据
	@RequestMapping(PATH_LIST)
	@ResponseBody
	public String infoList(XGridPage page,
			@RequestParam("cap_code") String capCode,
			@RequestParam("cap_name") String capName)
			throws InstantiationException, IllegalAccessException {
		String uid = getEntpUser().getUid();
		String sql = "from EntpSexhi info where info.uid='" + uid + "'";
		sql += sqlModel.getSQLChars("info.zhlx", "=", capCode, false, "and");
		sql += sqlModel.getSQLChars("info.zlhmc", "like", capName, false,
				"like");
		sql += " order by info.createtime desc";
		InfoGridRow row = new EntpSexhiAct.InfoGridRow();
		XGrid grid = entpSexhiMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	// 明细数据
	@RequestMapping(PATH_VIEW)
	public void infoView(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			@ModelAttribute("entpSexhi") EntpSexhi entpSexhiInfo, ModelMap model) {
		model.addAttribute("code", code);
		showSexhiView(entpSexhiInfo, model);
	}

	// 明细数据
	@RequestMapping(PATH_DETAIL)
	public void infoDetail(
			@RequestParam(value = "code", required = true, defaultValue = "") String code,
			@ModelAttribute("entpSexhi") EntpSexhi entpSexhiInfo, ModelMap model) {
		model.addAttribute("code", code);
		ExhiCfg cfg = getCfg();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		model.addAttribute("zbs",
				entpMng.findByProperty("userType", "Z", "createTime"));
		model.addAttribute("cbs",
				entpMng.findByProperty("userType", "C", "createTime"));
		// 小型展
		if ("S".equalsIgnoreCase(code)) {
			model.addAttribute("bdate", df.format(DateUtil.addDate(new Date(),
					cfg.getSt().intValue())));
		}
		if ("G".equalsIgnoreCase(code)) {
			model.addAttribute("bdate", df.format(DateUtil.addDate(new Date(),
					cfg.getCt().intValue())));
		}
		showSexhiView(entpSexhiInfo, model);
	}

	
	// 数据保存
	@RequestMapping(PATH_SAVE)
	public String saveInfo(
			HttpServletRequest request,
			@RequestParam(value = "projectId", required = true, defaultValue = "") String projectId,
			@ModelAttribute("entpSexhi") EntpSexhi entpSexhiInfo, ModelMap model)
			throws IllegalStateException, IOException {
		if (entpSexhiInfo.getId() == null) {
			entpSexhiInfo.setStatus("01");
			entpSexhiInfo.setUid(getEntpUser().getUid());
			entpSexhiInfo.setCreatetime(new Date());
			entpSexhiMng.save(entpSexhiInfo);
		} else {
			entpSexhiMng.update(entpSexhiInfo);
		}
		XMsg msg = new XMsg();
		String entpId = entpSexhiInfo.getId();
		if (projectId == null || !entpId.equalsIgnoreCase(projectId)) {
			/*
			 * relationMng.saveEntpRelation(projectId, entpId, "ZB");// 主办单位
			 * relationMng.saveEntpRelation(projectId, entpId, "CB");// 承办单位
			 * relationMng.saveEntpRelation(projectId, entpId, "ZC");// 支持单位
			 * relationMng.saveEntpRelation(projectId, entpId, "XB");// 协办单位
			 */
			relationMng.saveEntpRelation(projectId, entpId, "exhiType");// 展会类型
			relationMng.saveEntpRelation(projectId, entpId, "zldd");// 展会场馆

		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 小型国际展--场租协议&其他
		if (entpSexhiInfo.getZhlx().equalsIgnoreCase("S")) {
			if (saveUpload(multipartRequest, "attach1")) {
				attachMng.saveFileAttach(entpId, "CZXY");// 场租协议
			} else {
				msg.setState(false);
				msg.setMsg(attachMng.getErrors());
			}
			if (saveUpload(multipartRequest, "attach2")) {

				attachMng.saveFileAttach(entpId, "QT");// 其他
			} else {
				msg.setState(false);
				msg.setMsg(attachMng.getErrors());
			}
			log("小型展览会", " 已保存小型展览会申请", entpSexhiInfo.getId(), null);
		} else {
			log("国内展备案", " 已保存国内展备案申请", entpSexhiInfo.getId(), null);
		}
		msg.setState(true);

		return "redirect:" + PATH_VIEW.substring(1) + ".jspx?code="
				+ entpSexhiInfo.getZhlx() + "&infoId=" + entpSexhiInfo.getId();
	}

	@RequestMapping(PATH_SB)
	@ResponseBody
	public String bookSB(@ModelAttribute("entpSexhi") EntpSexhi entpSexhi,
			ModelMap model) {
		AuditLog audit = new AuditLog();
		if (entpSexhi.getZhlx().equalsIgnoreCase("S")) {
			if ("01".equalsIgnoreCase(entpSexhi.getStatus())
					|| "25".equalsIgnoreCase(entpSexhi.getStatus())
					|| "45".equalsIgnoreCase(entpSexhi.getStatus())) {
				entpSexhi.setStatus("20");
				entpSexhiMng.update(entpSexhi);
				audit.setAuditGroup("S");
				audit.setAuditId(entpSexhi.getId());
				audit.setAuditTitle("已提交小型展项目预约");
				audit.setAuditSendId("20");
				audit.setAuditTime(new Date());
				if (null != getEntpUser())
					audit.setAuditName(getEntpUser().getMc());
				audit.setAuditStatus("T");
				auditLogMng.save(audit);
				log("小型展览会", " 已提交小型展览会申请", entpSexhi.getId(), null);
			}
		} else {
			if ("01".equalsIgnoreCase(entpSexhi.getStatus())) {
				entpSexhi.setStatus("90");
				entpSexhiMng.update(entpSexhi);
				audit.setAuditGroup("G");
				audit.setAuditId(entpSexhi.getId());
				audit.setAuditTitle("已发布国内展备案");
				audit.setAuditTime(new Date());
				if (null != getEntpUser())
					audit.setAuditName(getEntpUser().getMc());
				audit.setAuditStatus("T");
				auditLogMng.save(audit);
				log("国内展备案", " 已提交国内展备案申请", entpSexhi.getId(), null);
			}
		}
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@RequestMapping(PATH_DELETE)
	@ResponseBody
	public String exhiEntpDelete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids) {
		delete("t_entp_sexhi", "eid", ids);
		return "";
	}

	@ModelAttribute("entpSexhi")
	public EntpSexhi getEntpSexhiInfo(
			@RequestParam(value = "infoId", required = true, defaultValue = "") String id) {
		EntpSexhi entpSexhi = entpSexhiMng.get(id);
		if (null == entpSexhi) {
			entpSexhi = new EntpSexhi();
		}
		return entpSexhi;
	}

	class InfoGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
			if (obj instanceof EntpSexhi) {
				xrow = new XGridRow();
				EntpSexhi info = (EntpSexhi) obj;
				xrow.setId(info.getId());
				List t = new ArrayList();
				t.add("");
				if ("S".equalsIgnoreCase(info.getZhlx()))
					t.add("小型国际展");
				if ("G".equalsIgnoreCase(info.getZhlx()))
					t.add("国内展");
				t.add(df1.format(info.getCreatetime()));
				t.add(info.getZlhmc());
				if ("S".equalsIgnoreCase(info.getZhlx()))
					t.add(getStatus(info.getStatus()));
				t.add(EntpSexhiAct.this.getBookUrl(info.getZhlx(),
						info.getId(), info.getStatus()));
				xrow.setData(t);
			}
			return xrow;
		}
	}
	
	public String getStatus(String code){
		if ("01".equalsIgnoreCase(code)){
			return "草稿";
		}
		
		if ("20".equalsIgnoreCase(code)){
			return "待核对";
		}
		
		if ("25".equalsIgnoreCase(code)){
			return "退回调整";
		}
		
		if ("30".equalsIgnoreCase(code)){
			return "信息已核对，请提交纸质材料";
		}
		
		if ("40".equalsIgnoreCase(code)){
			return "信息已核对，请提交纸质材料";
		}
		
		if ("45".equalsIgnoreCase(code)){
			return "材料退回";
		}
		
		if ("50".equalsIgnoreCase(code)){
			return "审查中";
		}		
		
		if ("70".equalsIgnoreCase(code)){
			return "审查中";
		}
		
		return "";
	}

	public String getBookUrl(String code, String href, String status) {
		String url = "";
		url += "<a href='small-view.jspx?code=" + code + "&infoId=" + href
				+ "' >【展览详情】</a>";
		if ("#01#25#45#35#".indexOf(status) > 0)
			url += "<a href='small-detail.jspx?code=" + code + "&infoId="
					+ href + "' >【修改】</a>";
		if ("#30#40#50#60#".indexOf(status) > 0)
			url += "<a target='_blank' href='print-corp-sexhi.jspx?code=" + code + "&sinfoId="
					+ href + "' >【打印材料】</a>";
		if ("#50#60#70#80#".indexOf(status) > 0 && "S".equalsIgnoreCase(code))
			url += "<a href='tp-detail.jspx?code=" + code + "infoId=" + href
					+ "'  >【台批】</a>";
		return url;
	}

	@Autowired
	@Qualifier("entpSexhiMng")
	private EntpSexhiMng entpSexhiMng;
}
